//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package tt.dz.biz.service.user;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.financial.MerchantDAO;
import tt.dz.biz.dao.user.OnlineAccountDAO;
import tt.dz.biz.dao.user.UserDAOImpl;
import tt.dz.biz.service.BaseService;
import tt.dz.biz.service.card.CardTypeService;
import tt.dz.biz.service.card.OnlineCardService;
import tt.dz.biz.service.common.CommonService;
import tt.dz.biz.service.order.OrderServiceService;
import tt.dz.common.BusinessException;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DateUtil;
import tt.dz.common.DzDigester;
import tt.dz.common.LogUtil;
import tt.dz.common.DzConstants.CardBIN;
import tt.dz.common.DzConstants.CardType;
import tt.dz.common.DzConstants.cardState;
import tt.dz.common.DzConstants.userLock;
import tt.dz.common.DzConstants.userRegistChannelType;
import tt.dz.common.DzConstants.userType;
import tt.dz.common.DzConstants.userValid;
import tt.dz.common.DzErrorCode.ExceptionErrorCode;
import tt.dz.vo.IdentityAccountVO;
import tt.dz.vo.MerchantVO;
import tt.dz.vo.OfflineAccountVO;
import tt.dz.vo.OnlineAccountVO;
import tt.dz.vo.Operator;
import tt.dz.vo.OrderServiceVO;
import tt.dz.vo.UserBaseVO;
import tt.dz.vo.UserDetailVO;
import tt.dz.vo.UserRelationshipVO;
import tt.dz.vo.UserServiceVO;

@Service("userService")
public class UserService extends BaseService {
    @Resource(
        name = "userDAO"
    )
    private UserDAOImpl userDao;
    @Resource(
        name = "merchantDAO"
    )
    private MerchantDAO merchantDAO;
    @Resource(
        name = "cardTypeServiceImpl"
    )
    private CardTypeService cardTypeService;
    @Resource(
        name = "userServiceService"
    )
    private UserServiceService userServiceService;
    @Resource(
        name = "orderServiceService"
    )
    private OrderServiceService orderServiceService;
    @Resource(
        name = "onlineAccountDAO"
    )
    private OnlineAccountDAO onlineAccountDAO;
    @Resource(
        name = "identityAccountService"
    )
    private IdentityAccountService identityAccountService;
    @Resource(
        name = "offlineAccountService"
    )
    OfflineAccountService offlineAccountService;
    @Resource(
        name = "onlineCardService"
    )
    OnlineCardService onlineCardService;
    @Resource(
        name = "commonService"
    )
    private CommonService commonService;

    public UserService() {
    }

    public Operator queryUserBynameAndPassword(Operator user) {
        return this.userDao.queryUserByNameAndPwd(user);
    }

    public boolean checkMerchantExists(String merchantCode) throws Exception {
        return this.merchantDAO.queryMerchantByCode(merchantCode) != null;
    }

    public boolean checkMobileExists(String mobileNo, String merchantCode) throws Exception {
        try {
            UserBaseVO userBase = this.userDao.getUserBaseByUserId((String)null, mobileNo, merchantCode);
            return userBase != null;
        } catch (IncorrectResultSizeDataAccessException var4) {
            LogUtil.error("通过手机查询出多条用户信息,手机号码为：" + mobileNo + ",运营商编码为：" + merchantCode);
            return true;
        }
    }

    public int saveregister(UserBaseVO userBase, UserDetailVO userDetail) {
        int result = this.userDao.insertUserByBase(userBase);
        this.userDao.insertUserByDetail(userDetail);

        try {
            List<OrderServiceVO> defaultServiceList = this.orderServiceService.queryDefaultService();
            if(CollectionUtils.isNotEmpty(defaultServiceList)) {
                List<UserServiceVO> userServiceList = new ArrayList(defaultServiceList.size());
                UserServiceVO userServiceVO = null;
                Date now = DateUtil.getDBCurrentTime();
                Iterator var9 = defaultServiceList.iterator();

                while(var9.hasNext()) {
                    OrderServiceVO orderServiceVO = (OrderServiceVO)var9.next();
                    userServiceVO = new UserServiceVO();
                    userServiceVO.setServiceNo(orderServiceVO.getServiceNo());
                    userServiceVO.setUserId(userBase.getUserId());
                    userServiceVO.setIsValid(userValid.VALID.value());
                    userServiceVO.setCreatedTime(now);
                    userServiceVO.setUpdatedTime(now);
                    userServiceVO.setCreatedBy("sys");
                    userServiceVO.setUpdatedBy("sys");
                    userServiceList.add(userServiceVO);
                }

                this.userServiceService.batchInsertUserService(userServiceList);
            }
        } catch (Exception var10) {
            LogUtil.error("插入用户可用服务异常，用户id为：" + userBase.getUserId(), var10);
        }

        return result;
    }

    public int saveRegisterAndOnlineCard(UserBaseVO userBase, UserDetailVO userDetail, String areaCode) {
        int result = this.saveregister(userBase, userDetail);
        if(StringUtils.isBlank(areaCode)) {
            areaCode = "0028";
        }

        OnlineAccountVO onlineVO = this.generateOnlineAccount(areaCode, userBase.getUpdatedBy());
        onlineVO.setUserId(userBase.getUserId());
        if(!this.insertOnlineAccount(onlineVO)) {
            throw new BusinessException(ExceptionErrorCode.COMMON_EXCEPTION.value(), ExceptionErrorCode.COMMON_EXCEPTION.getDesc(), ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
        } else {
            return result;
        }
    }

    public String queryUserSequence() {
        return this.userDao.queryUserSequence();
    }

    public List<UserBaseVO> queryCorpUsers(UserBaseVO userBaseVO) {
        try {
            return this.userDao.queryCorpUsers(userBaseVO);
        } catch (Exception var3) {
            LogUtil.error("查询企业客户异常", var3);
            return new ArrayList();
        }
    }

    public List<UserBaseVO> queryUserByUserType(Integer userType) {
        try {
            return this.userDao.queryUserByUserType(userType);
        } catch (Exception var3) {
            LogUtil.error("根据客户类型查询客户异常", var3);
            return new ArrayList();
        }
    }

    public List<UserBaseVO> queryEnterpriseUser() {
        Object userBaseList = null;

        try {
            userBaseList = this.userDao.queryEnterpriseUser();
        } catch (Exception var3) {
            LogUtil.error("查询企业用户异常", var3);
            userBaseList = new ArrayList();
        }

        return (List)userBaseList;
    }

    public boolean updateEnterpriseUser(UserBaseVO userBaseVO) {
        boolean excuteFlag = false;

        try {
            int i = this.userDao.updateEnterpriseUser(userBaseVO);
            excuteFlag = i > 0;
        } catch (Exception var4) {
            LogUtil.error("更新企业用户异常--入参：" + userBaseVO.toString(), var4);
        }

        return excuteFlag;
    }

    public String getUserId(userType userType, userRegistChannelType channelType) {
        String userSeq = this.queryUserSequence();
        String userId = userType.value() + channelType.value() + DateUtil.getDateFormatter() + DZStringUtil.getFixedLengthString(8, userSeq);
        return userId;
    }

    public void saveUploadCorpUsers(List<UserBaseVO> userlist) throws Exception {
        try {
            UserDetailVO userDetail = null;
            String uid = null;
            String salt = null;
            Date dbTtime = this.commonService.getDBCurrentTime();
            Iterator var7 = userlist.iterator();

            while(var7.hasNext()) {
                UserBaseVO userBase = (UserBaseVO)var7.next();
                uid = this.getUserId(userType.ENTERPRISE_CUSTOMER, userRegistChannelType.MAINSERVER);
                salt = DZStringUtil.getRandomString(6);
                userBase.setUserId(uid);
                userBase.setRegistTime(dbTtime);
                userBase.setCreatedTime(dbTtime);
                userBase.setUserType(userType.ENTERPRISE_CUSTOMER.value());
                userBase.setPassword(DzDigester.md5ForUser(userBase.getPassword(), salt));
                userBase.setIsLocked(userLock.UNLOCK.value());
                userBase.setSalt(salt);
                userDetail = new UserDetailVO();
                userDetail.setUserId(uid);
                this.saveRegisterAndOnlineCard(userBase, userDetail, "9999");
            }

        } catch (Exception var8) {
            LogUtil.error("批量导入企业用户异常，入参userlist为：" + userlist, var8);
            throw var8;
        }
    }

    public List<UserBaseVO> queryUserBaseList() {
        return this.userDao.queryUserBaseList();
    }

    public boolean updateUserLockByUserId(String userId, userLock userlock) {
        boolean excuteFlag = false;

        try {
            int i = this.userDao.updateUserLockByUserId(userId, userlock);
            excuteFlag = i > 0;
        } catch (Exception var5) {
            LogUtil.error("更新用户锁定信息异常--入参 userID：" + userId + ",userlock:" + userlock, var5);
        }

        return excuteFlag;
    }

    public List<UserBaseVO> queryUserBase(UserBaseVO userBaseVO) {
        Object userBaseList = null;

        try {
            userBaseList = this.userDao.queryUserBase(userBaseVO);
        } catch (Exception var4) {
            LogUtil.error("根据传入条件查询用户异常", var4);
            userBaseList = new ArrayList();
        }

        return (List)userBaseList;
    }

    public boolean updateUserByBase(UserBaseVO userBaseVO) {
        boolean excuteFlag = false;

        try {
            int i = this.userDao.updateUserByBase(userBaseVO);
            excuteFlag = i > 0;
        } catch (Exception var4) {
            LogUtil.error("更新用户异常--入参：" + userBaseVO.toString(), var4);
        }

        return excuteFlag;
    }

    public List<UserBaseVO> queryUserByMerchant(MerchantVO merchantVO) {
        Object userBaseList = null;

        try {
            userBaseList = this.userDao.queryUserByMerchant(merchantVO);
        } catch (Exception var4) {
            LogUtil.error("根据运营商查询用户异常--入参：" + merchantVO.toString(), var4);
            userBaseList = new ArrayList();
        }

        return (List)userBaseList;
    }

    public Map<String, Object> parseExcelToUser(InputStream inStream) {
        Map<String, Object> rs = new HashMap();
        String[] file_header = new String[]{"手机"};
        CSVParser csvFileParser = null;
        InputStreamReader in = new InputStreamReader(inStream);
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(file_header);

        HashMap var16;
        try {
            csvFileParser = new CSVParser(in, csvFileFormat);
            List<CSVRecord> csvRecords = csvFileParser.getRecords();
            CSVRecord record = null;
            List<UserBaseVO> userList = new ArrayList();
            String mobileNo = null;
            StringBuilder errorMsg = new StringBuilder();
            UserBaseVO paramUser = new UserBaseVO();
            UserBaseVO userBaseVO = null;

            for(int i = 1; i < csvRecords.size(); ++i) {
                record = (CSVRecord)csvRecords.get(i);
                mobileNo = record.get(file_header[0]);
                if(StringUtils.isBlank(mobileNo)) {
                    errorMsg.append("第" + (i + 1) + "行用户手机空;");
                } else {
                    paramUser.setMobileNo(mobileNo);
                    userBaseVO = this.userDao.querySingleUserByMobile(paramUser);
                    if(userBaseVO == null) {
                        errorMsg.append("第" + (i + 1) + "行手机号" + mobileNo + "没有在系统中创建用户！;");
                    } else {
                        userList.add(userBaseVO);
                    }
                }
            }

            rs.put("msg", errorMsg.toString());
            rs.put("dataList", userList);
            return rs;
        } catch (Exception var24) {
            LogUtil.error("CSV转换对象异常", var24);
            rs.put("msg", "CSV转换对象异常");
        } finally {
            try {
                in.close();
                csvFileParser.close();
            } catch (IOException var23) {
                LogUtil.error("转换CSV关闭文件流异常", var23);
            }

        }

        return rs;
    }

    public boolean batchUpdateUser(List<UserBaseVO> userList) {
        boolean excuteFlag = true;

        try {
            int[] iArray = this.userDao.batchUpdateUser(userList);
            int[] var7 = iArray;
            int var6 = iArray.length;

            for(int var5 = 0; var5 < var6; ++var5) {
                int i = var7[var5];
                if(i < 0) {
                    excuteFlag = false;
                    break;
                }
            }
        } catch (Exception var8) {
            LogUtil.error("批量更新用户异常", var8);
        }

        return excuteFlag;
    }

    public UserBaseVO querySingleUser(UserBaseVO userBaseVO) {
        try {
            userBaseVO = this.userDao.querySingleUser(userBaseVO);
            return userBaseVO;
        } catch (Exception var3) {
            LogUtil.error("根据userid查询单个用户异常--入参" + userBaseVO.getUserId(), var3);
            userBaseVO = null;
            throw new BusinessException(ExceptionErrorCode.COMMON_EXCEPTION.value(), ExceptionErrorCode.COMMON_EXCEPTION.getDesc(), var3.getMessage());
        }
    }

    public boolean allotUser(UserBaseVO destUser, UserBaseVO sourceUser, String sysCode) {
        boolean excuteFlag = false;

        try {
            UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
            userRelationshipVO.setUserId(sourceUser.getUserId());
            userRelationshipVO.setRelateUserId(destUser.getUserId());
            List<UserRelationshipVO> list = this.userDao.queryUserRelationship(userRelationshipVO);
            if(list.isEmpty()) {
                userRelationshipVO.setIsValid(Integer.valueOf(1));
                userRelationshipVO.setRelateTime(new Date());
                userRelationshipVO.setSysCode(sysCode);
                int i = this.userDao.insertUserRelationship(userRelationshipVO);
                excuteFlag = i > 0;
            } else {
                excuteFlag = true;
            }

            return excuteFlag;
        } catch (Exception var8) {
            LogUtil.error("绑定身份识别卡异常", var8);
            throw new BusinessException(ExceptionErrorCode.COMMON_EXCEPTION.value(), ExceptionErrorCode.COMMON_EXCEPTION.getDesc(), var8.getMessage());
        }
    }

    public OnlineAccountVO generateOnlineAccount(String areaCode, String userId) {
        OnlineAccountVO onlineAccountVO = new OnlineAccountVO();
        onlineAccountVO.setUserId(userId);
        onlineAccountVO.setCardBin(CardBIN.CARDBIN_188.value());
        onlineAccountVO.setCardType(CardType.ONLINE_CARD.value());
        onlineAccountVO.setAreaCode(DZStringUtil.getFixedLengthString(4, areaCode));
        onlineAccountVO.setState(cardState.ACTIVATE.value());
        onlineAccountVO.setOpenDate(DateUtil.getDBCurrentTime());
        onlineAccountVO = this.createBusinessId(onlineAccountVO);
        return onlineAccountVO;
    }

    public OnlineAccountVO createBusinessId(OnlineAccountVO onlineAccountVO) {
        StringBuilder builder = new StringBuilder("");
        builder.append(onlineAccountVO.getCardBin());
        builder.append(onlineAccountVO.getCardType());
        builder.append(onlineAccountVO.getAreaCode());
        builder.append(String.valueOf(this.userDao.querySequence("online_account_seq")));
        String verifyCode = String.valueOf(DZStringUtil.createVerifyCode(builder.toString()));
        builder.append(verifyCode);
        onlineAccountVO.setCheckCode(verifyCode);
        onlineAccountVO.setCardNo(builder.toString());
        return onlineAccountVO;
    }

    public boolean insertOnlineAccount(OnlineAccountVO onlineAccountVO) {
        try {
            int i = this.onlineAccountDAO.insertOnlineAccount(onlineAccountVO);
            return i > 0;
        } catch (Exception var3) {
            LogUtil.error("插入虚拟上线卡异常", var3);
            return false;
        }
    }

    public List<Map<String, Object>> queryCardState(List<String> cardNoList) throws Exception {
        try {
            String cardType = null;
            Map<String, Object> cardInfo = null;
            boolean cardTypeIsRight = false;
            IdentityAccountVO identifyVO = null;
            OnlineAccountVO onlineVO = null;
            List<OfflineAccountVO> offlineList = null;
            OfflineAccountVO offlineAccoutParam = null;
            List<Map<String, Object>> rsList = new ArrayList();
            if(CollectionUtils.isEmpty(cardNoList)) {
                return new ArrayList();
            } else {
                Iterator var11 = cardNoList.iterator();

                while(var11.hasNext()) {
                    String cardNo = (String)var11.next();
                    cardInfo = new HashMap();
                    cardInfo.put("cardNo", cardNo);
                    cardType = this.cardTypeService.getCardType(cardNo);
                    CardType[] var15;
                    int var14 = (var15 = CardType.values()).length;

                    for(int var13 = 0; var13 < var14; ++var13) {
                        CardType tmp = var15[var13];
                        if(tmp.value().equals(cardType)) {
                            cardTypeIsRight = true;
                            break;
                        }
                    }

                    if(!cardTypeIsRight) {
                        cardInfo.put("cardState", cardState.CARD_TYPE_ERROR.value());
                        rsList.add(cardInfo);
                    } else {
                        cardInfo.put("cardType", cardType);
                        if(CardType.IDENTITY_CARD.value().equals(cardType)) {
                            identifyVO = this.identityAccountService.queryIdentifyCardByNo(cardNo);
                            if(identifyVO == null) {
                                cardInfo.put("cardState", cardState.CARD_NOT_FOUND.value());
                            } else {
                                cardInfo.put("cardState", identifyVO.getState());
                            }
                        } else if(CardType.OFFLINE_CARD.value().equals(cardType)) {
                            offlineAccoutParam = new OfflineAccountVO();
                            offlineAccoutParam.setCardNo(cardNo);
                            offlineList = this.offlineAccountService.queryOfflineAccount(offlineAccoutParam);
                            if(CollectionUtils.isEmpty(offlineList)) {
                                cardInfo.put("cardState", cardState.CARD_NOT_FOUND.value());
                            } else {
                                cardInfo.put("cardState", ((OfflineAccountVO)offlineList.get(0)).getState());
                            }
                        } else if(CardType.ONLINE_CARD.value().equals(cardType)) {
                            onlineVO = this.onlineAccountDAO.queryOnlineCardByNo(cardNo);
                            if(onlineVO == null) {
                                cardInfo.put("cardState", cardState.CARD_NOT_FOUND.value());
                            } else {
                                cardInfo.put("cardState", onlineVO.getState());
                            }
                        }

                        rsList.add(cardInfo);
                    }
                }

                return rsList;
            }
        } catch (Exception var16) {
            LogUtil.error("查询卡状态异常", var16);
            throw var16;
        }
    }
}